<template>
  <div
    ref="swiper_box"
    class="swiper_box"
    @mouseup="mouseup"
    @mousedown="mousedown"
    @mousemove="mousemove"
    @mouseleave="mouseleave"
    @mouseenter="mouseenter"
  >
    <div
      class="swiper_img_box"
      :class="{ transition: isTransition }"
      :style="`transform: translateX(${position}px)`"
    >
      <slot>
        <div
          class="swiper_img"
          :style="`height: ${getHeigth};`"
          v-for="(i, index) in list"
          :key="index"
          @click.stop="imgClick(index)"
        >
          <img :src="i" />
        </div>
      </slot>
    </div>
    <div v-if="isIndicator" class="dot_box">
      <div
        class="dot_item"
        v-for="(i, index) in list"
        :key="index"
        :style="`background:${
          index === activationIndex ? activationColor : inactivationColor
        };`"
        @click.stop="dotClick(index)"
      ></div>
    </div>
    <!-- 预览图片 -->
    <Preview
      v-if="isLargeImage"
      :list="list"
      :index="activationIndex"
      @close="isLargeImage = false"
    />
  </div>
</template>

<script>
import Preview from "./preview.vue";
export default {
  /**
   * Swiper  轮播图
   * @description 本组件一般用于展示轮播图的地方，可利用插槽自定义项(* 注意使用插槽时请设置插槽项 width: 100%;flex-shrink: 0; 不然可能会出现无法沾满的情况)。
   * @property {Array}			      list				        图片数组,数组里面直接放图片url 例：['http:***'] (* 如果是自定义插槽也把list传进来，这样才可实现左右滑动)
   * @property {String | Number}	heigth			        轮播图高度默认 200px (使用插槽时无效，需要用内容撑开)
   * @property {Boolean}	        isIndicator			    是否显示指示标（小圆点）默认 true
   * @property {String}	          activationColor		  小圆点激活的颜色 默认 #409eff
   * @property {String}	          inactivationColor	  小圆点失激活的颜色 默认 #a0a0a0
   * @property {Number}	          threshold	          拖动阈值 默认 200
   * @property {Number}	          switchTime	        多久切换一次默认 3000 毫秒（* 如果设置为0则取消自动切换）
   * @property {Boolean}	        isLargeImageClick	  是否点击显示完整图 默认 true (* 如果使用插槽则无效)
   * @event    {Function}         change              点击事件，返回点击的下标(* 如果使用插槽则无效)
   * @example  <Swiper :list="list"></Swiper>
   */
  components: {
    Preview,
  },
  props: {
    // 图片数组,数组里面直接放url (* 如果是自定义插槽也把list传进来，这样才可实现左右滑动)
    list: {
      default: () => [],
      type: Array,
    },
    // 轮播图高度
    heigth: {
      default: 200,
      type: [String, Number],
    },
    // 是否显示指示标（小圆点）
    isIndicator: {
      default: true,
      type: Boolean,
    },
    // 小圆点激活的颜色
    activationColor: {
      default: "#409eff",
      type: String,
    },
    // 小圆点失激活的颜色
    inactivationColor: {
      default: "#a0a0a0",
      type: String,
    },
    // 拖动阈值
    threshold: {
      default: 200,
      type: Number,
    },
    // 多久切换一次（毫秒）
    switchTime: {
      default: 3000,
      type: Number,
    },
    // 是否点击显示完整图
    isLargeImageClick: {
      default: true,
      type: Boolean,
    },
  },
  computed: {
    getHeigth() {
      if (typeof this.heigth === "number") {
        return this.heigth + "px";
      } else {
        return this.heigth;
      }
    },
  },
  data() {
    return {
      // 轮播图宽度
      slideWidth: 0,
      // 当前激活图片list的下标
      activationIndex: 0,
      // 鼠标是否进入swiper_box
      isDown: false,
      // 当前轮播图的偏移量
      position: 0,
      // 鼠标按下时的初始X坐标
      startX: 0,
      // 拖动动画阈值
      dragThreshold: 5,
      // 最后一次拖动的距离
      distance: 0,
      // 开始点击的坐标位置
      oneStartX: 0,
      // 结束的坐标位置
      endX: 0,
      // 定时器
      timeObj: null,
      // 是否开启过渡
      isTransition: true,
      // 是否显示大图
      isLargeImage: false,
    };
  },
  mounted() {
    this.timeEvent();
    this.$nextTick(() => {
      this.slideWidth = this.$refs.swiper_box.clientWidth;
    });
  },
  // 卸载前关闭定时器
  beforeUnmount() {
    clearInterval(this.timeObj);
  },
  methods: {
    // 点击图片项
    imgClick(index) {
      if (Math.abs(this.oneStartX - this.endX) < 3) {
        if (this.isLargeImageClick) {
          this.isLargeImage = true;
        }
        this.$emit("change", index);
      }
    },
    // 点击指示标（小圆点）事件
    dotClick(index) {
      this.activationIndex = index;
      this.position = -(this.activationIndex * this.slideWidth);
    },
    // 定时切换
    timeEvent() {
      if (this.switchTime == 0) return;
      this.timeObj = setInterval(() => {
        if (this.activationIndex >= this.list.length - 1) {
          this.activationIndex = 0;
        } else {
          this.activationIndex++;
        }
        this.position = -(this.activationIndex * this.slideWidth);
      }, this.switchTime);
    },
    // 设置滑动到哪一个
    setActivationItem() {
      if (this.distance > 0) {
        if (Math.abs(this.oneStartX - this.endX) >= this.threshold) {
          this.activationIndex -= 1;
        }
      } else {
        if (Math.abs(this.oneStartX - this.endX) >= this.threshold) {
          this.activationIndex += 1;
        }
      }
      if (this.activationIndex < 0) {
        this.activationIndex = 0;
      } else if (this.activationIndex > this.list.length - 1) {
        this.activationIndex = this.list.length - 1;
      }
      this.position = -(this.activationIndex * this.slideWidth);
      this.isDown = false;
    },
    // 当鼠标按下元素时触发
    mousedown(event) {
      this.isTransition = false;
      this.isDown = true;
      this.startX = event.clientX;
      this.oneStartX = event.clientX;
    },
    // 当鼠标释放元素时触发
    mouseup(event) {
      this.isTransition = true;
      this.endX = event.clientX;
      if (this.isDown) {
        this.setActivationItem();
      }
    },
    // 当鼠标进入元素时触发
    mouseenter() {
      clearInterval(this.timeObj);
    },
    // 当鼠标离开元素时触发
    mouseleave() {
      this.isTransition = true;
      this.timeEvent();
      this.position = -(this.activationIndex * this.slideWidth);
      this.isDown = false;
    },
    // 当鼠标在元素内移动时触发
    mousemove(event) {
      if (this.isDown) {
        this.distance = event.clientX - this.startX;
        // 检查是否达到拖动阈值
        if (Math.abs(this.distance) >= this.dragThreshold) {
          // 根据鼠标滑动的距离调整轮播图的偏移量
          this.position += this.distance;
          // 重置起始X坐标
          this.startX = event.clientX;
        }
      }
    },
  },
};
</script>

<style scoped>
.swiper_box {
  width: 100%;
  position: relative;
  border-radius: 15px;
  border: #d9d9d9 1px solid;
  background: #d9d9d9;
  overflow: hidden;
}
.swiper_img_box {
  width: 100%;
  display: flex;
}
.transition {
  transition: all 0.5s 0s;
}
.swiper_img {
  flex-shrink: 0;
  width: 100%;
  cursor: pointer;
}
.swiper_img img {
  height: 100%;
  width: 100%;
  user-drag: none;
  -webkit-user-drag: none; /* 兼容 WebKit 浏览器（例如 Chrome、Safari） */
  -moz-user-drag: none; /* 兼容 Firefox 浏览器 */
  -ms-user-drag: none; /* 兼容 Internet Explorer 浏览器 */
}
/* 指示标样式 */
.dot_box {
  position: absolute;
  bottom: 10px;
  width: 100%;
  display: flex;
  justify-content: center;
}
.dot_item {
  margin: 0 10px;
  width: 10px;
  height: 10px;
  border-radius: 100%;
  cursor: pointer;
}
/* 大图样式 */
.large_image_box {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 2023;
  background: #303133;
  /* opacity: 0.5; */
  display: flex;
  justify-content: center;
  align-items: center;
}
.large_image_but {
  background: #000000;
  opacity: 0.8;
  width: 44px;
  height: 44px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 100%;
  cursor: pointer;
}
.large_image_but div {
  position: relative;
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.large_image_but div div {
  background: white;
  width: 24px;
  height: 3px;
  border-radius: 3px;
  position: absolute;
}
/* 关闭按钮 */
.large_image_close {
  position: absolute;
  top: 50px;
  right: 50px;
}
.large_image_close div div:nth-child(1) {
  transform: rotate(45deg);
  transform-origin: center;
}
.large_image_close div div:nth-child(2) {
  transform: rotate(-45deg);
  transform-origin: center;
}
/* 左边按钮 */
.large_image_left {
  position: absolute;
  left: 50px;
}
.large_image_left div div:nth-child(1) {
  width: 18px;
  transform: rotate(35deg);
  transform-origin: left;
}
.large_image_left div div:nth-child(2) {
  width: 18px;
  transform: rotate(-35deg);
  transform-origin: left;
}
/* 右边按钮 */
.large_image_right {
  position: absolute;
  right: 50px;
}
.large_image_right div div:nth-child(1) {
  width: 18px;
  transform: rotate(-35deg);
  transform-origin: right;
}
.large_image_right div div:nth-child(2) {
  width: 18px;
  transform: rotate(35deg);
  transform-origin: right;
}
</style>
